package com.qm.interceptor;

import com.qm.pojo.User;
import com.qm.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 @author james
 @create 2021-04-30 10:23
 mvc提供的对外的拦截器接口
 */

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisCluster jedisCluster;

    /**
     * [目  的]：如果用户不登录，则不允许访问权限相关业务
     * [返回值]：true：表示放行    false：表示拦截 一般配置重定向使用
     * [使用事项]：必须添加拦截器策略
     * [业务说明]:
     * 	 用户如果已经登录,则放行,反正拦截
     * [如何判断用户是否登录]:
     * 	1.判断客户端是否有指定的Cookie    true
     * 	2.应该获取cookie中的值  去redis中校验是否存在.  true
     *  如果上述条件都满足,则应该放行请求.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                if ("QM_TICKET".equals(cookie.getName())) {
                    String ticket = cookie.getValue();
                    if (jedisCluster.exists(ticket)){
                        String userJSON = jedisCluster.get(ticket);
                        User user = ObjectMapperUtil.toObject(userJSON, User.class);
                        request.setAttribute("QM_USER", user);
                        return true;
                    }
                }
            }
        }
        response.sendRedirect("/user/login.html");
        return false;
    }
}
